import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { getCart, addToCart, updateCartItem, removeCartItem, clearCartItems } from '@/api/modules/cart'
import type { CartVO, CartItemVO, CartAddDTO, Product } from '@/types'

export const useCartStore = defineStore('cart', {
    state: () => ({
        cart: null as CartVO | null,
        loading: false,
    }),

    getters: {
        // 购物车商品
        items: (state) => state.cart?.items ?? [],

        // 购物车商品数量
        itemCount: (state) => state.cart?.totalItems ?? 0,

        // 选中的商品数量
        selectedCount: (state) => state.cart?.items.filter(item => item.selected).length ?? 0,

        // 购物车总积分
        totalPoints: (state) => {
            return state.cart?.items
                .filter(item => item.selected)
                .reduce((total, item) => total + (item.points * item.quantity), 0) ?? 0
        },

        // 购物车总商品数
        totalQuantity: (state) => {
            return state.cart?.items
                .filter(item => item.selected)
                .reduce((total, item) => total + item.quantity, 0) ?? 0
        },

        // 是否全选
        isAllSelected: (state) => {
            if (!state.cart || state.cart.items.length === 0) return false
            return state.cart.items.every(item => item.selected)
        },
    },

    actions: {
        // 从服务器获取购物车
        async fetchCart() {
            this.loading = true
            try {
                const cartData = await getCart()
                // 后端返回的购物车项没有 selected 属性，我们在前端添加它
                this.cart = {
                    ...cartData,
                    items: cartData.items.map(item => ({ ...item, selected: true }))
                }
            } catch (error) {
                console.error('获取购物车失败:', error)
                ElMessage.error('获取购物车失败')
            } finally {
                this.loading = false
            }
        },

        // 添加商品到购物车
        async addToCart(product: Product | CartAddDTO) {
            this.loading = true
            try {
                // 如果传入的是Product对象，转换为CartAddDTO
                const dto: CartAddDTO = 'productId' in product 
                    ? product 
                    : { productId: product.id, quantity: 1 }
                
                await addToCart(dto)
                ElMessage.success('已加入购物车')
                await this.fetchCart() // 重新获取购物车
            } catch (error) {
                console.error('添加购物车失败:', error)
                ElMessage.error('添加购物车失败')
            } finally {
                this.loading = false
            }
        },

        // 检查商品是否在购物车中
        isInCart(productId: number): boolean {
            return this.cart?.items.some(item => item.productId === productId) ?? false
        },

        // 更新商品数量
        async updateQuantity(productId: number, quantity: number) {
            if (quantity <= 0) {
                await this.removeFromCart(productId)
                return
            }
            this.loading = true
            try {
                await updateCartItem(productId, quantity)
                await this.fetchCart() // 重新获取购物车
            } catch (error) {
                console.error('更新商品数量失败:', error)
                ElMessage.error('更新商品数量失败')
            } finally {
                this.loading = false
            }
        },

        // 从购物车移除商品
        async removeFromCart(productId: number) {
            this.loading = true
            try {
                await removeCartItem(productId)
                ElMessage.success('已从购物车移除')
                await this.fetchCart() // 重新获取购物车
            } catch (error) {
                console.error('移除商品失败:', error)
                ElMessage.error('移除商品失败')
            } finally {
                this.loading = false
            }
        },

        // 切换商品选中状态 (本地操作)
        toggleSelection(productId: number) {
            const item = this.cart?.items.find(item => item.productId === productId)
            if (item) {
                item.selected = !item.selected
            }
        },

        // 全选/取消全选 (本地操作)
        toggleAllSelection() {
            if (!this.cart) return
            const allSelected = this.isAllSelected
            this.cart.items.forEach(item => {
                item.selected = !allSelected
            })
        },

        // 清空购物车中选中的商品
        async clearSelected() {
            if (!this.cart) return
            const selectedItems = this.cart.items.filter(item => item.selected)
            if (selectedItems.length === 0) return

            const productIds = selectedItems.map(item => item.productId)

            this.loading = true
            try {
                await clearCartItems(productIds)
                ElMessage.success('已清空选中的商品')
                await this.fetchCart() // 重新获取购物车
            } catch (error) {
                console.error('清空失败:', error)
                ElMessage.error('清空失败')
            } finally {
                this.loading = false
            }
        },

        // 获取选中的商品
        getSelectedItems(): CartItemVO[] {
            return this.cart?.items.filter(item => item.selected) ?? []
        },
    },
})
